﻿/*
	Class			Canvas
	Package			forms.Canvas
	
	Description		Replaces the use of Sprite, to include custom methods and properties.

	Usage			Scales an object proportionally:
					
					myCanvas.scale = 1;    vs    myCanvas.scaleX = myCanvas.scaleY = 1;
					
	
					Three ways to center align a Canvas object:
					
					myCanvas.center (coordinateSpace:Rectangle);
					myCanvas.center (relativeToObject:DisplayObject);
					myCanvas.center (width:Number, height:Number);
					
	History			1.0		6/03/07		Created
	
	Todo			n/a
*/

package pete.old
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	public class Canvas extends Sprite
	{
		private var scaleValue:Number;
		
		public function Canvas ()
		{
			
		}
		
		
		public function get scale ():Number
		{
			return this.scaleValue;
		}
		
		
		public function set scale (scaleValue:Number):void
		{
			this.scaleValue = scaleValue;
			this.scaleX = this.scaleY = scaleValue;
		}
		
		
		public function center (...args):void
		{
			var offsetX:Number;
			var offsetY:Number;
			var centerX:Number;
			var centerY:Number;
			
			if (args[0] is Rectangle)
			{
				var coordinateSpace:Rectangle = args[0];
				
				offsetX = coordinateSpace.x;
				offsetY = coordinateSpace.y;
				centerX = (coordinateSpace.width / 2) - (this.width / 2);
				centerY = (coordinateSpace.height / 2) - (this.height / 2);
			}
			
			else if (args[0] is DisplayObject)
			{
				var relativeToObject:DisplayObject = args[0];
				var objectBounds:Rectangle         = relativeToObject.getBounds (relativeToObject);
				var relativeBounds:Rectangle       = this.getBounds (relativeToObject);
				
				var objectX:Number   = objectBounds.x * relativeToObject.scaleX;
				var objectY:Number   = objectBounds.y * relativeToObject.scaleY;
				var relativeX:Number = relativeBounds.x * relativeToObject.scaleX;
				var relativeY:Number = relativeBounds.y * relativeToObject.scaleY;
				
				offsetX = this.x + objectX - relativeX;
				offsetY = this.y + objectY - relativeY;
				centerX = (relativeToObject.width / 2) - (this.width / 2);
				centerY = (relativeToObject.height / 2) - (this.height / 2);
				
			}
			
			else if (args[0] is Number && args[1] is Number)
			{
				var relativeWidth:Number  = args[0];
				var relativeHeight:Number = args[1];
				
				offsetX = 0;
				offsetY = 0;
				centerX = (relativeWidth / 2) - (this.width / 2);
				centerY = (relativeHeight / 2) - (this.height / 2);
			}
			
			this.x = Math.round (offsetX + centerX);
			this.y = Math.round (offsetY + centerY);
		}
		
	}
}